package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.integration.DictIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.ComplaintTypeEnum;
import com.jwsoft.manager.common.enums.EnrollStatusFormalEnum;
import com.jwsoft.manager.common.enums.SocialSecurityDictEnum;
import com.jwsoft.manager.common.enums.SourceTypeEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.common.AreaControlVO;
import com.jwsoft.manager.common.vo.eduSocialSecurity.EduSocialSecurityKeyVO;
import com.jwsoft.manager.common.vo.eduSocialSecurity.EduSocialSecurityQueryVO;
import com.jwsoft.manager.common.vo.eduSocialSecurity.EduSocialSecurityVO;
import com.jwsoft.manager.common.vo.individuation.CbSaveVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduSocialSecurityIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.util.EduDesensitizeUtil;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.InvocationTargetException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 参保记录表业务实现类
 *
 * @author wangtao
 * @since 2022-12-28
 */
@ApiService(funcCode = "EduSocialSecurity", title = "参保记录表")
public class EduSocialSecurityIntegrationImpl implements EduSocialSecurityIntegration {

    @Autowired
    public EduSocialSecurityService eduSocialSecurityService;
    @Autowired
    public EduSchoolService eduSchoolService;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;
    @Autowired
    private CommonIntegration commonIntegration;
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private OperationCacheIntegration operationCacheIntegration;
    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;
    @Autowired
    private EduComplaintService eduComplaintService;
    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private DictIntegration dictIntegration;


    @Autowired
    private DictHelper dictHelper;
    public static final String APP_SB_LIMIT = "APP_SB_LIMIT_";
    public static final String get_sb = "APP_SB_IDCARD_";

    @Autowired
    private  EduDataTaskDetailService eduDataTaskDetailService;

    @Autowired
    public EduhSocialSecurityService eduhSocialSecurityService;

    @Autowired
    private static final String STUDENT_SOCIAL_SECURITY = "edu_social_security";

    @Override
    @OpApi(funcCode = "EduSocialSecurity0001", title = "参保记录表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduSocialSecurityVO> getList(EduSocialSecurityQueryVO vo) {
        List<String> areaCodeList = getAreaCodeList(vo);
        if (CollectionUtils.isEmpty(areaCodeList)) {
            throw new AppException("必须传入行政区划");
        }
        //取出脱敏字段，判断是否为空
        Boolean desensitizeFlag = vo.getDesensitizeFlag();
        if (desensitizeFlag == null) {
            desensitizeFlag = true;
        }
        //判断是否迁移
        boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(), STUDENT_SOCIAL_SECURITY);
        // 根据是否查询历史表，调用不同方法
        if (!queryHistoryFlag) {
            LambdaQueryWrapper<EduSocialSecurity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(EduSocialSecurity::getAab301, areaCodeList);
            if (!ObjectUtils.isEmpty(vo.getAac147())) {
                queryWrapper.eq(EduSocialSecurity::getAac147, vo.getAac147());
            }
            if (!ObjectUtils.isEmpty(vo.getAac003())) {
                queryWrapper.eq(EduSocialSecurity::getAac003, vo.getAac003());
            }
            if (!ObjectUtils.isEmpty(vo.getAab004())) {
                queryWrapper.like(EduSocialSecurity::getAab004, vo.getAab004());
            }
            if (!ObjectUtils.isEmpty(vo.getAac031())) {
                queryWrapper.eq(EduSocialSecurity::getAac031, vo.getAac031());
            }
            if (!ObjectUtils.isEmpty(vo.getAac008())) {
                queryWrapper.eq(EduSocialSecurity::getAac008, vo.getAac008());
            }
            if (!ObjectUtils.isEmpty(vo.getSourceType())) {
                queryWrapper.eq(EduSocialSecurity::getSourceType, vo.getSourceType());
            }
            if (!ObjectUtils.isEmpty(vo.getAac058())) {
                queryWrapper.eq(EduSocialSecurity::getAac058, vo.getAac058());
            }
            if (!ObjectUtils.isEmpty(vo.getYear())) {
                queryWrapper.eq(EduSocialSecurity::getYear, vo.getYear());
            }

            // 开启分页
            if (vo.getPageNum() == null || vo.getPageSize() == null) {
                //如果不传入分页参数，默认最大取1000条
                vo.setPageNum(1);
                vo.setPageSize(1000);
            }
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduSocialSecurity> list = eduSocialSecurityService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduSocialSecurity> pageInfo = new PageInfo<>(list);

            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduSocialSecurityVO> resultList = Convert.toList(EduSocialSecurityVO.class, pageInfo.getList());
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(SocialSecurityDictEnum.values()));

            //脱敏
            if (desensitizeFlag) {
                for (EduSocialSecurityVO eduSocialSecurityVO : resultList) {
                    eduSocialSecurityVO.setAac003(EduDesensitizeUtil.desensitizeFullName(eduSocialSecurityVO.getAac003()));
                    eduSocialSecurityVO.setAac147(EduDesensitizeUtil.desensitizeIdcard(eduSocialSecurityVO.getAac147()));
                    eduSocialSecurityVO.setAac002(EduDesensitizeUtil.desensitizeOther(eduSocialSecurityVO.getAac002()));
                    eduSocialSecurityVO.setAab001(EduDesensitizeUtil.desensitizeOther(eduSocialSecurityVO.getAab001()));
                    eduSocialSecurityVO.setBab010(EduDesensitizeUtil.desensitizeOther(eduSocialSecurityVO.getBab010()));
                }
            }
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        } else {
            // 迁移过后，判断是否加密
            Boolean encryptFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), STUDENT_SOCIAL_SECURITY));
            //如果加密，把查询条件加密
            if (encryptFlag) {
                if (StringUtils.isNotBlank(vo.getAac003())) {
                    vo.setAac003(CommonSecureUtil.sm4Encrypt(vo.getAac003()));
                }
                if (StringUtils.isNotBlank(vo.getAac147())) {
                    vo.setAac147(CommonSecureUtil.sm4Encrypt(vo.getAac147()));
                }
            }
            LambdaQueryWrapper<EduhSocialSecurity> eduhSocialSecurityWrapper =  new LambdaQueryWrapper<>();
            eduhSocialSecurityWrapper.in(EduhSocialSecurity::getAab301, areaCodeList);
            if (!ObjectUtils.isEmpty(vo.getAac147())) {
                eduhSocialSecurityWrapper.eq(EduhSocialSecurity::getAac147, vo.getAac147());
            }
            if (!ObjectUtils.isEmpty(vo.getAac003())) {
                eduhSocialSecurityWrapper.eq(EduhSocialSecurity::getAac003, vo.getAac003());
            }
            if (!ObjectUtils.isEmpty(vo.getAab004())) {
                eduhSocialSecurityWrapper.like(EduhSocialSecurity::getAab004, vo.getAab004());
            }
            if (!ObjectUtils.isEmpty(vo.getAac031())) {
                eduhSocialSecurityWrapper.eq(EduhSocialSecurity::getAac031, vo.getAac031());
            }
            if (!ObjectUtils.isEmpty(vo.getAac008())) {
                eduhSocialSecurityWrapper.eq(EduhSocialSecurity::getAac008, vo.getAac008());
            }
            if (!ObjectUtils.isEmpty(vo.getSourceType())) {
                eduhSocialSecurityWrapper.eq(EduhSocialSecurity::getSourceType, vo.getSourceType());
            }
            if (!ObjectUtils.isEmpty(vo.getAac058())) {
                eduhSocialSecurityWrapper.eq(EduhSocialSecurity::getAac058, vo.getAac058());
            }
            if (!ObjectUtils.isEmpty(vo.getYear())) {
                eduhSocialSecurityWrapper.eq(EduhSocialSecurity::getYear, vo.getYear());
            }

            // 开启分页
            if (vo.getPageNum() == null || vo.getPageSize() == null) {
                //如果不传入分页参数，默认最大取1000条
                vo.setPageNum(1);
                vo.setPageSize(1000);
            }
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduhSocialSecurity> list = eduhSocialSecurityService.list(eduhSocialSecurityWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduhSocialSecurity> pageInfo = new PageInfo<>(list);

            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduSocialSecurityVO> resultList = Convert.toList(EduSocialSecurityVO.class, pageInfo.getList());
            //解密
            for (EduSocialSecurityVO eduSocialSecurityVO : resultList) {
                if ("1".equals(eduSocialSecurityVO.getEncryptFlag())){
                    if (StringUtils.isNotBlank(eduSocialSecurityVO.getAac003())) {
                        eduSocialSecurityVO.setAac003(CommonSecureUtil.sm4Decrypt(eduSocialSecurityVO.getAac003()));
                    }
                    if (StringUtils.isNotBlank(eduSocialSecurityVO.getAac147())) {
                        eduSocialSecurityVO.setAac147(CommonSecureUtil.sm4Decrypt(eduSocialSecurityVO.getAac147()));
                    }
                }
            }
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(SocialSecurityDictEnum.values()));

            //脱敏
            if (desensitizeFlag) {
                for (EduSocialSecurityVO eduSocialSecurityVO : resultList) {
                    eduSocialSecurityVO.setAac003(EduDesensitizeUtil.desensitizeFullName(eduSocialSecurityVO.getAac003()));
                    eduSocialSecurityVO.setAac147(EduDesensitizeUtil.desensitizeIdcard(eduSocialSecurityVO.getAac147()));
                    eduSocialSecurityVO.setAac002(EduDesensitizeUtil.desensitizeOther(eduSocialSecurityVO.getAac002()));
                    eduSocialSecurityVO.setAab001(EduDesensitizeUtil.desensitizeOther(eduSocialSecurityVO.getAab001()));
                    eduSocialSecurityVO.setBab010(EduDesensitizeUtil.desensitizeOther(eduSocialSecurityVO.getBab010()));
                }
            }
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }
    }

    private List<String> getAreaCodeList(EduSocialSecurityQueryVO vo) {
        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAab301())) {
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
            if ("330701".equalsIgnoreCase(sessionAreaCode)) {
                areaCodeList.add("330799");
            }
        } else {
            areaCodeList.add(vo.getAab301());
            if ("330701".equalsIgnoreCase(vo.getAab301())) {
                areaCodeList.add("330799");
            }
        }
        return areaCodeList;
    }

    @Override
    @OpApi(funcCode = "EduSocialSecurity0002", title = "参保记录表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduSocialSecurityVO getById(EduSocialSecurityKeyVO vo) {
        //判断是否迁移过
        EduSocialSecurityVO result;
        Boolean queryHistoryFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyQueryHistory(vo.getYear(), STUDENT_SOCIAL_SECURITY));
        if (!queryHistoryFlag) {
            // 没有迁移查询
            EduSocialSecurity entity = eduSocialSecurityService.getById(vo.getSocialSecurityId());
            if (ObjectUtils.isEmpty(entity)) {
                throw new AppException("查询不到详细信息!");
            }
            result = Convert.convert(EduSocialSecurityVO.class, entity);
        }else {
            EduhSocialSecurity eduhSocialSecurity = eduhSocialSecurityService.getById(vo.getSocialSecurityId());

            if (ObjectUtils.isEmpty(eduhSocialSecurity)) {
                throw new AppException("查询不到详细信息!");
            }
            //解密
            if ("1".equals(eduhSocialSecurity.getEncryptFlag())){
                if (StringUtils.isNotBlank(eduhSocialSecurity.getAac003())) {
                    eduhSocialSecurity.setAac003(CommonSecureUtil.sm4Decrypt(eduhSocialSecurity.getAac003()));
                }
                if (StringUtils.isNotBlank(eduhSocialSecurity.getAac147())) {
                    eduhSocialSecurity.setAac147(CommonSecureUtil.sm4Decrypt(eduhSocialSecurity.getAac147()));
                }
            }
            result = Convert.convert(EduSocialSecurityVO.class, eduhSocialSecurity);
        }

        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "EduSocialSecurity0003", title = "参保记录表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSocialSecurityVO vo) {
        //校验是否存在重复数据
        //1、同年度同身份证通险种，不能重复
        LambdaQueryWrapper<EduSocialSecurity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSocialSecurity::getDel,0);
        queryWrapper.eq(EduSocialSecurity::getYear,vo.getYear());
        queryWrapper.eq(EduSocialSecurity::getAac147,vo.getAac147());
        queryWrapper.eq(EduSocialSecurity::getAae140,vo.getAae140());
        if(!ObjectUtils.isEmpty(vo.getSocialSecurityId())){
            queryWrapper.ne(EduSocialSecurity::getSocialSecurityId,vo.getSocialSecurityId());
        }
        if(eduSocialSecurityService.count(queryWrapper)!=0){
            throw new AppException("存在同年度重复数据，请核对!");
        }

    }

    @Override
    @OpApi(funcCode = "EduSocialSecurity0004", title = "参保记录表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "EduSocialSecurity0004",
            operationName = "参保记录表新增",
            dataType = "socialSecurityId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSocialSecurityVO add(EduSocialSecurityVO vo) {
        //根据登录账号判断是学校还是管理员

        String orgid = SessionUtil.getOrgId();
        //根据组织编码判断数据来源是否是学校录入
        LambdaQueryWrapper<EduSchool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSchool::getDel,0);
        queryWrapper.eq(EduSchool::getOrgId,orgid);
        if(eduSchoolService.count(queryWrapper)==0){
            vo.setSourceType(SourceTypeEnum.admin.getType());
        }else{
            vo.setSourceType(SourceTypeEnum.school.getType());
        }
        if (StringUtils.isNotBlank(vo.getContinuityFlag())){
            vo.setContinuityFlag("1");
        }
        //保存前校验
        checkSave(vo);

        Boolean enrollFlag = checkEnroll(vo.getAac147(),vo.getYear());
        if (enrollFlag){
            throw new AppException("已存在报名数据，无法进行修改！!");
        }
        //保存数据
        EduSocialSecurity entity = Convert.convert(EduSocialSecurity.class, vo);
        eduSocialSecurityService.save(entity);
        clearCache(entity.getAac147());
        //将主键设置回vo使操作日志可以取到
        vo.setSocialSecurityId(entity.getSocialSecurityId());
        return vo;
    }


    private Boolean checkEnroll(String idcard, Integer year) {
        if(year==null){
            EduOperationCacheDetailVO eduOperationCacheDetailVO=operationCacheIntegration.getPeriodYear();
            year=eduOperationCacheDetailVO.getYear();
        }
        List<String> enrollStatusList=new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper =new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnroll::getIdcard).eq(EduStudentEnroll::getIdcard,idcard)
                .eq(EduStudentEnroll::getYear,year)
                .in(EduStudentEnroll::getEnrollStatus,enrollStatusList);
        if(eduStudentEnrollService.count(enrollQueryWrapper)<=0){
            return false;
        }
        return true;
    }

    @Override
    @OpApi(funcCode = "EduSocialSecurity0005", title = "参保记录表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "EduSocialSecurity0005",
            operationName = "参保记录表修改",
            dataType = "socialSecurityId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSocialSecurityVO edit(EduSocialSecurityVO vo) {
        Boolean queryHistoryFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyQueryHistory(vo.getYear(), STUDENT_SOCIAL_SECURITY));
        if (queryHistoryFlag) {
            throw new AppException("历史数据无法修改");
        }
        if (ObjectUtils.isEmpty(vo.getSocialSecurityId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSocialSecurity oldEntity = eduSocialSecurityService.getById(vo.getSocialSecurityId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }


        String orgid = SessionUtil.getOrgId();
        System.out.println("orgid是："+orgid);

        LambdaQueryWrapper<EduSchool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSchool::getDel,0);
        queryWrapper.eq(EduSchool::getOrgId,orgid);
        if(eduSchoolService.count(queryWrapper)==0){
            vo.setSourceType(SourceTypeEnum.admin.getType());
        }else{
            vo.setSourceType(SourceTypeEnum.admin.getType());
        }
        //保存前校验
        checkSave(vo);
        Boolean enrollFlag = checkEnroll(vo.getAac147(),vo.getYear());
        if (enrollFlag){
            throw new AppException("已存在报名数据，无法进行修改！!");
        }
        //保存数据
        EduSocialSecurity entity = Convert.convert(EduSocialSecurity.class, vo);
        eduSocialSecurityService.updateById(entity);
        clearCache(entity.getAac147());
        return vo;
    }

    @Override
    @OpApi(funcCode = "EduSocialSecurity0006", title = "参保记录表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "EduSocialSecurity0006",
            operationName = "参保记录表删除",
            dataType = "socialSecurityId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSocialSecurityKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getSocialSecurityId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSocialSecurity entity = eduSocialSecurityService.getById(vo.getSocialSecurityId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        Boolean enrollFlag = checkEnroll(entity.getAac147(),entity.getYear());
        if (enrollFlag){
            throw new AppException("已存在报名数据，无法进行修改！!");
        }
        eduSocialSecurityService.removeById(vo.getSocialSecurityId());
        clearCache(entity.getAac147());
    }
    //清除缓存
    private void clearCache(String idcard){
        //查询人员
        if(StringUtils.isBlank(idcard)){
            return;
        }

        QueryWrapper<EduStudentEnrollPre> queryPreWrapper=new QueryWrapper<>();
        queryPreWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId,EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                .and( wrapper -> {
                    wrapper.eq(EduStudentEnrollPre::getIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                            .or()
                            .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                });
        List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryPreWrapper);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        for (EduStudentEnrollPre pre:list) {
            //社保
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }
    @Override
    @OpApi(funcCode = "EduSocialSecurity0007", title = "获取参保信息并保存", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE,savelog = false)
    public List<EduSocialSecurityVO> getSocialSecurityAndSave(CbSaveVO vo) {
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        ApiModel apiModel=eduHelper.getEduFunc("saveCbInterfaceData",vo.getAreaCode());
        try {
            Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
            if (null != bean) {
                List<EduSocialSecurityVO> list= (List<EduSocialSecurityVO>) apiModel.getMethod().invoke(bean, vo);
                if(!CollectionUtils.isEmpty(list)){
                    List<EduSocialSecurityVO> retVO=new ArrayList<>();
                    for(EduSocialSecurityVO eduSocialSecurityVO :list){
                        if(eduSocialSecurityVO.getAae140().equalsIgnoreCase("110")
                        ||eduSocialSecurityVO.getAae140().equalsIgnoreCase("120")){
                            retVO.add(eduSocialSecurityVO);
                        }
                    }
                    return retVO;
                }
            }else {
                throw new AppException("未查询到方法");
            }
        }catch (AppException e ){
            throw e;
        }catch (InvocationTargetException e ){
            try{
                AppException exception= (AppException) e.getTargetException();
                throw new AppException(exception.getMsg(),e.getTargetException());
            }catch (Exception ex){
                throw new AppException(e.getCause().getMessage(),e.getTargetException());
            }

        }catch (Exception e ){
            throw new AppException( e.getMessage(),e);
        }
        return new ArrayList<>();
    }

    @Override
    @OpApi(funcCode = "EduSocialSecurity0008", title = "家长端获取参保信息并保存", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE,savelog = false)
    public List<EduSocialSecurityVO> getAppSocialSecurityAndSave(CbSaveVO vo) {
        String idcard=vo.getIdcard();
        boolean flag=false;
        if(StringUtils.isBlank(idcard)){
            idcard=SessionUtil.getSessionInfo().getIdcard();
            flag=true;
        }

        //同一身份证一天最多同步获取3次
        String key = get_sb+idcard;
        Integer getCount= (Integer) redisHelper.get(key);
        if(getCount==null||getCount==0){
            getCount=1;
        }else{
            getCount=getCount+1;
        }
        redisHelper.set(key,getCount,43200);
        if(getCount>3){
            throw new AppException("24小时内最多获取三次，如还有问题，请致电联系");
        }
        Object maxObj = redisHelper.get(APP_SB_LIMIT + DateUtil.today());
        int max;
        if (org.springframework.util.ObjectUtils.isEmpty(maxObj)) {
            redisHelper.set(APP_SB_LIMIT + DateUtil.today(), 1);
            max = 1;
        } else {
            max = (int) redisHelper.get(APP_SB_LIMIT + DateUtil.today());
            max++;
            redisHelper.set(APP_SB_LIMIT + DateUtil.today(), max);
        }
        CommonVO commonVO=new CommonVO();
        commonVO.setParamKey("APP_SB_LIMIT");
        String limit = commonIntegration.getValueByKey(commonVO);
        if (!org.springframework.util.ObjectUtils.isEmpty(limit) && max > Integer.parseInt(limit)) {
            throw new AppException("今日大数据接口已达上限，请明日再试！");
        }
        List<EduSocialSecurityVO> retList=new ArrayList<>();
        Integer year = operationCacheIntegration.getPeriodYear().getYear();
        final String finalId=idcard;
        QueryWrapper<EduStudentEnrollPre> studentEnrollPreQueryWrapper = new QueryWrapper<>();
        studentEnrollPreQueryWrapper
                .lambda().select(EduStudentEnrollPre::getIdcard,EduStudentEnrollPre::getFullName,
                EduStudentEnrollPre::getFatherIdcard,EduStudentEnrollPre::getFatherName,
                EduStudentEnrollPre::getMotherName,EduStudentEnrollPre::getMotherIdcard)
                .eq(EduStudentEnrollPre::getYear, year)
                .and(
                        wrapper -> {
                            wrapper.eq(EduStudentEnrollPre::getFatherIdcard, finalId)
                                    .or()
                                    .eq(EduStudentEnrollPre::getIdcard, finalId)
                                    .or()
                                    .eq(EduStudentEnrollPre::getMotherIdcard, finalId);
                        }).orderByAsc(EduStudentEnrollPre::getIdcard);
        List<EduStudentEnrollPre> queryList =
                eduStudentEnrollPreService.list(studentEnrollPreQueryWrapper);
        if(flag){
            if(CollectionUtils.isEmpty(queryList)){
                return new ArrayList<>();
            }
            List<String> idcardList=new ArrayList<>();
            for(EduStudentEnrollPre eduStudentEnrollPre:queryList){
                Boolean enrollFlag= this.checkEnroll(eduStudentEnrollPre.getIdcard(),year);
                if(enrollFlag){
                    throw new AppException("已存在报名数据，不能重新获取数据!");
                }
            }
            for(EduStudentEnrollPre eduStudentEnrollPre:queryList){
                if(StringUtils.isNotBlank(eduStudentEnrollPre.getFatherIdcard())&&!idcardList.contains(eduStudentEnrollPre.getFatherIdcard())){
                    idcardList.add(eduStudentEnrollPre.getFatherIdcard());
                    CbSaveVO saveVO=new CbSaveVO();
                    saveVO.setIdcard(eduStudentEnrollPre.getFatherIdcard());
                    saveVO.setName(eduStudentEnrollPre.getFatherName());
                    saveVO.setReplaceFlag(true);
                    retList.addAll(getSocialSecurityAndSave(saveVO));
                }
                if(StringUtils.isNotBlank(eduStudentEnrollPre.getMotherIdcard())&&!idcardList.contains(eduStudentEnrollPre.getMotherIdcard())){
                    idcardList.add(eduStudentEnrollPre.getMotherIdcard());
                    CbSaveVO saveVO=new CbSaveVO();
                    saveVO.setIdcard(eduStudentEnrollPre.getMotherIdcard());
                    saveVO.setName(eduStudentEnrollPre.getMotherName());
                    saveVO.setReplaceFlag(true);
                    retList.addAll(getSocialSecurityAndSave(saveVO));
                }
            }
        }else{
            CbSaveVO saveVO=new CbSaveVO();
            saveVO.setIdcard(vo.getIdcard());
            saveVO.setName(vo.getName());
            saveVO.setReplaceFlag(true);
            retList.addAll(getSocialSecurityAndSave(saveVO));
        }
        if(!CollectionUtils.isEmpty(queryList)){
            EduStudentEnrollPre pre=queryList.get(0);
            if(StringUtils.isNotBlank(pre.getIdcard())){
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getIdcard());
            }
            if(StringUtils.isNotBlank(pre.getFatherIdcard())){
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getFatherIdcard());
            }
            if(StringUtils.isNotBlank(pre.getMotherIdcard())){
                eduEnrollClearCacheHelper.clearCacheMyEnrollPreSb(pre.getMotherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnrollPre(pre.getMotherIdcard());
            }
            for(EduStudentEnrollPre studentEnrollPre:queryList){
                eduEnrollClearCacheHelper.clearCachePreBefore(studentEnrollPre.getStudentEnrollPreId());
            }
        }
        return retList;

    }

    @Override
    @OpApi(funcCode = "EduSocialSecurity0009", title = "家长端当年适龄子女获取参保信息", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE,savelog = false)
    public List<EduSocialSecurityVO> getAppSocialSecurityList(AreaControlVO vo) {
        String idcard=SessionUtil.getSessionInfo().getIdcard();
        if(StringUtils.isBlank(idcard)){
            throw new AppException("用户的证件号码不能为空");
        }
        String key=idcard;
        Cache<String, List<EduSocialSecurityVO>> cache = JetCacheUtils.create(EduCache.EDU_MY_ENROLL_PRE_SB, CacheType.BOTH, Duration.ofHours(6), Duration.ofSeconds(20));
        List<EduSocialSecurityVO> value=  cache.get(key);
        if(value!=null){
            return value;
        }
        Integer year = operationCacheIntegration.getPeriodYear().getYear();
        List<String> areaCodeList=new ArrayList<>();
        if(StringUtils.isBlank(vo.getAreaCode())){
            String areaCode=eduHelper.thisAreaCode();
            vo.setAreaCode(areaCode);
            DictAreaVO dictAreaVO = new DictAreaVO();
            dictAreaVO.setParentId(areaCode);
            dictAreaVO.setPermissionFlag(false);
            List<SelectVO> districtByOrg = dictIntegration.getDistrictByOrg(dictAreaVO);
            if(!CollectionUtils.isEmpty(districtByOrg)){
                areaCodeList=districtByOrg.stream().map(SelectVO::getDictKey).distinct().collect(Collectors.toList());
                if(areaCodeList.contains("330701")){
                    areaCodeList.add("330799");
                }
            }else{
                areaCodeList.add(areaCode);
                if(areaCode.equalsIgnoreCase("330701")){
                    areaCodeList.add("330799");
                }

            }

        }else{
            areaCodeList.add(vo.getAreaCode());
            if(vo.getAreaCode().equalsIgnoreCase("330701")){
                areaCodeList.add("330799");
            }
        }
        QueryWrapper<EduStudentEnrollPre> studentEnrollPreQueryWrapper = new QueryWrapper<>();
        studentEnrollPreQueryWrapper
                .lambda()
                .eq(EduStudentEnrollPre::getYear, year)
                .and(
                        wrapper -> {
                            wrapper.eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                        }).orderByAsc(EduStudentEnrollPre::getIdcard);
        List<EduStudentEnrollPre> queryList =
                eduStudentEnrollPreService.list(studentEnrollPreQueryWrapper);
        if(CollectionUtils.isEmpty(queryList)){
            return new ArrayList<>();
        }
        List<String> idcardList=new ArrayList<>();
        for(EduStudentEnrollPre eduStudentEnrollPre:queryList){
            if(StringUtils.isNotBlank(eduStudentEnrollPre.getFatherIdcard())&&!idcardList.contains(eduStudentEnrollPre.getFatherIdcard())){
                idcardList.add(eduStudentEnrollPre.getFatherIdcard());
            }
            if(StringUtils.isNotBlank(eduStudentEnrollPre.getMotherIdcard())&&!idcardList.contains(eduStudentEnrollPre.getMotherIdcard())){
                idcardList.add(eduStudentEnrollPre.getMotherIdcard());
            }
        }

        List<String> aae140List = new ArrayList<>();
        aae140List.add("110");
        aae140List.add("120");
        QueryWrapper<EduSocialSecurity> securityQueryWrapper = new QueryWrapper<>();
        securityQueryWrapper.lambda().eq(EduSocialSecurity::getYear, year)
                .in(EduSocialSecurity::getAab301, areaCodeList)
                .in(EduSocialSecurity::getAac147, idcardList)
                .in(EduSocialSecurity::getAae140, aae140List)
                .eq(EduSocialSecurity::getAac008, "1")
                .orderByAsc(EduSocialSecurity::getAac147).orderByAsc(EduSocialSecurity::getAae140).orderByAsc(EduSocialSecurity::getAae030);
        List<EduSocialSecurity> socialSecurityList = eduSocialSecurityService.list(securityQueryWrapper);
        List<EduSocialSecurityVO> cbVOList =new ArrayList<>();
        if (!CollectionUtils.isEmpty(socialSecurityList)) {
            for(EduSocialSecurity eduSocialSecurity:socialSecurityList){
                EduSocialSecurityVO eduSocialSecurityVO=Convert.convert(EduSocialSecurityVO.class,eduSocialSecurity);
                eduSocialSecurityVO.setAae140Name(dictHelper.getValue("AAE140",eduSocialSecurity.getAae140()));
                eduSocialSecurityVO.setAab301Name(dictHelper.getValue("AREA",eduSocialSecurity.getAab301()));
                if("1".equalsIgnoreCase(eduSocialSecurity.getAac008())){
                    if("1".equalsIgnoreCase(eduSocialSecurity.getAac031())){
                        eduSocialSecurityVO.setStatus("1");
                        eduSocialSecurityVO.setStatusName("正常参保");
                    }else{
                        eduSocialSecurityVO.setStatus("2");
                        eduSocialSecurityVO.setStatusName("参保中断");
                    }
                }else{
                    eduSocialSecurityVO.setStatus("3");
                    eduSocialSecurityVO.setStatusName("参保终止");
                }
                QueryWrapper<EduComplaint> queryWrapper=new QueryWrapper<>();
                queryWrapper.lambda().select(EduComplaint::getHandleStatus).eq(EduComplaint::getType, ComplaintTypeEnum.sb.getType())
                        .eq(EduComplaint::getHandleStatus,BoolEnum.FALSE.getType())
                        .eq(EduComplaint::getOtherId,eduSocialSecurityVO.getSocialSecurityId());
                List<EduComplaint> complaints=eduComplaintService.list(queryWrapper);
                if(!CollectionUtils.isEmpty(complaints)){
                    eduSocialSecurityVO.setSbHandleStatus(complaints.get(0).getHandleStatus());
                }
                cbVOList.add(eduSocialSecurityVO);
            }
            cache.put(key,cbVOList);
            return cbVOList;
        }
        cache.put(key,new ArrayList<>());
        return new ArrayList<>();
    }
}
